import { _decorator, director, instantiate, Node, ParticleSystem, Prefab, resources, Vec3 } from 'cc';
import { Pools } from '../utils/Pools';
const { ccclass, property } = _decorator;

@ccclass('EffectManager')
export class EffectManager {

    private static _instance: EffectManager = null;

    static get instance(): EffectManager {
        if (this._instance == null) {
            this._instance = new EffectManager();
        }

        return this._instance;
    }

    pools:Pools<string, Node> = new Pools();

    init(onComplete:()=>void){
        resources.loadDir("effect/Prefab", Prefab, (err: Error, Prefabs:Prefab[])=>{
            // 生成内存池
            for(let prefab of Prefabs){
                this.pools.newPool(prefab.name, (): Node => {
                    let node = instantiate(prefab);
                    director.getScene().addChild(node);
                    node.active = false;
                    return node;
                }, 10, (node:Node)=>{
                    node.removeFromParent()
                })
            }

            onComplete();
        })
    }

    destroy(){
        this.pools.destroyAll();
    }


    play(key: string, position: Vec3)
    {
        let node = this.pools.allocc(key);
        node.active = true;
        node.worldPosition = position;

        let particleSystem = node.getComponent(ParticleSystem);
        particleSystem.play();

        particleSystem.schedule(() => {
            this.pools.free(key, node)
        }, particleSystem.duration)
    }

  
}

